var GoogleCalendar = require('google-calendar');
var say = require('say');
var fs = require('fs');

exports.google_calendar = new GoogleCalendar.GoogleCalendar(
	'702444405811.apps.googleusercontent.com', 
	'p7CcT0kZwXj54dAjho1VwB29',
	'https://localhost:2002/authenticationGoogle'
);

exports.access_token = null;


exports.setTokens = function(access_token, refresh_token)
{
	exports.access_token = access_token;
}

/**

callback is of the form :

	function(err, text)

err is set to false if everything went OK.
text contains the speech for today's events.

**/

function getTodayEvents(token, callback)
{

	//if(exports.access_token != null)
	//{

		exports.google_calendar.listCalendarList(exports.access_token, function(err, calendarList) {

		    if(err == null || Object.keys(err).length == 0)
		    {

		    	if(Object.keys(err).length == 0) // si err est un objet vide {}
	        		calendarList = JSON.parse(calendarList); // débuggage bizarre au cas où le JSON n'est pas déjà parsé. Cela semble arriver quand err n'est pas null mais un objet vide...


				if(calendarList['items'])
				{
					var l = calendarList['items'].length;
					var texte = "";
					var calendar = null;

					for(var i = 0; i < l; i++)
					{
						if(calendarList.items[i].summary == 'GHOME')
							var calendar = calendarList.items[i];
					}

					if(calendar != null)
					{

						var timeMin = new Date();
						timeMin.setHours(0);
						timeMin.setMinutes(0);

						var timeMax = new Date();
						timeMax.setHours(23);
						timeMax.setMinutes(59);

						exports.google_calendar.listEvent(exports.access_token, calendar.id, function(err, events) {

							if(typeof events == 'string')
							{
	        					events = JSON.parse(events);
	        					err = null;
	        				}

							if(err != null || events == undefined)
							{
								console.log('Cannot read events of calendar "GHOME". Response:\n\n'+JSON.stringify(events));
								callback(true);
							}
							else
							{
								texte = 'Salut beau gosse, voici ton emploi du temps du jour : '
								for(var j = 0; j < events.items.length; j++)
								{
									var date = new Date(events.items[j].start.dateTime);
									if(date >= timeMin && date <= timeMax)
										texte += date.getHours() + ' heures ' + events.items[j].summary + ', ';
								}
								texte += '. Amuses toi bien, bonne journée !';
								callback(false, texte);
							}
						});
					}
					else
					{
						console.log('Could not find calendar named "GHOME". Response:\n\n'+JSON.stringify(calendarList));
						callback(true);
					}

				}
				else
				{
					console.log('Calendar items do not exist. Response:\n\n'+JSON.stringify(calendarList));
					callback(true);
				}

		    }
		    else
		    {
		    	console.log('Could not connect to google calendar with access_token: '+exports.access_token+', cleared token. Response:\n\n'+JSON.stringify(calendarList));
		    	exports.token = null;
		    	callback(true);
		    }

		});
	/*}
	else
	{
		console.log('No access_token available to access google calendar API.');
		callback(true);
	}*/

}


function sayCalendar(token)
{
	getTodayEvents(token, function(err, text)
	{
		if(err == false)
			say.speak('Audrey', text);
	});
}


exports.sayCalendar = sayCalendar;
exports.getTodayEvents = getTodayEvents;
